/**
 * 全局JS
 * @author liujie
 */
(function ($){

    //全局系统对象
    window['security'] = {};
    
    security.cookies = (function (){
        var fn = function (){
        };
        /**
         * 根据名称 获取cookie
         * @param name
         * @returns {String}
         */
        fn.prototype.get = function (name){
            var cookieValue = "";
            var search = name + "=";
            if (document.cookie.length > 0){
                offset = document.cookie.indexOf(search);
                if (offset != -1){
                    offset += search.length;
                    end = document.cookie.indexOf(";", offset);
                    if (end == -1) end = document.cookie.length;
                    cookieValue = decodeURIComponent(document.cookie.substring(offset, end));
                }
            }
            return cookieValue;
        };
        
        /**
         * 设置cookie
         * @param cookieName
         * @param cookieValue
         * @param DayValue
         */
        fn.prototype.set = function (cookieName, cookieValue, DayValue) {
            var expire = "";
            var day_value = 1;
            if (DayValue != null) {
                day_value = DayValue;
            }
            expire = new Date((new Date()).getTime() + day_value * 86400000);
            expire = "; expires=" + expire.toGMTString();
            document.cookie = cookieName + "=" + encodeURIComponent(cookieValue) + ";path=/" + expire;
        };
        
        /**
         * 删除cookie
         * @param cookieName
         */
        fn.prototype.remvoe = function (cookieName) {
            var expire = "";
            expire = new Date((new Date()).getTime() - 1);
            expire = "; expires=" + expire.toGMTString();
            document.cookie = cookieName + "=" + escape("") + ";path=/" + expire;
            /*path=/*/
        };

        return new fn();
    })();

    
    //预加载图片
    security.prevLoadImage = function (rootpath, paths) {
        for (var i in paths) {
            $('<img />').attr('src', rootpath + paths[i]);
        }
    };
    
    security.isIE = function (){
    	return window.navigator.userAgent.indexOf("MSIE") >= 0;
    };
    
    security.isChrome = function (){
    	return window.navigator.userAgent.indexOf("Chrome") >= 0;
    };
    
    
    security.isFireFox = function(){
    	return window.navigator.userAgent.indexOf("Firefox") >= 0;
    };
    
    var load_obj = null;
    
    //显示loading
    security.showLoading = function (message) {
    	load_obj = layer.load(0);
    };
    //隐藏loading
    security.hideLoading = function (message) {
    	if(null != load_obj) {
    		layer.close(load_obj);
    	}
    };
    //显示成功提示窗口
    security.showSuccess = function (message, callback) {
        if (typeof (message) == "function" || arguments.length == 0) {
            callback = message;
            message = "操作成功!";
        }
        layer.msg(message, 1, callback);
    };
    //显示失败提示窗口
    security.showError = function (message, callback) {
        if (typeof (message) == "function" || arguments.length == 0) {
            callback = message;
            message = "操作失败!";
        }
        layer.msg(message, 3, callback);
    };
    
    /**
     * 1 一个对勾  8哭脸
     * @param message
     */
    security.alert = function(message) {
    	layer.alert(message, 1); //风格一
    };


    //提交服务器请求
    //返回json格式
    //1,提交给类 options.type  方法 options.method 处理
    //2,并返回 AjaxResult(这也是一个类)类型的的序列化好的字符串
    security.ajax = function (options) {
        var p = options || {};
        var ashxUrl = options.ashxUrl;
        var url = p.url || ashxUrl + $.param({ type: p.type, method: p.method });
        $.ajax({
            cache: false,
            async: true,
            url: url,
            data: p.data,
            dataType: 'json', type: 'post',
            beforeSend: function () {
            	security.loading = true;
                if (p.beforeSend)
                    p.beforeSend();
                else
                	security.showLoading(p.loading);
            },
            complete: function () {
            	security.loading = false;
                if (p.complete)
                    p.complete();
                else
                	security.hideLoading();
            },
            success: function (result) {
                if (!result) return;
                if (result.success) {
                    if (p.success)
                        p.success(result.code, result.msg);
                }
                else {
                    if (p.error)
                        p.error(result.msg);
                }
            },
            error: function (result, b) {
            	//security.tip('发现系统错误 <BR>错误码：' + result.code);
            	layer.msg(result.msg, 3);
            }
        });
    };

    
    //提示 验证错误信息
    security.showInvalid = function (validator) {
        validator = validator || security.validator;
        if (!validator) return;
        var message = '<div class="invalid">存在' + validator.errorList.length + '个字段验证不通过，请检查!</div>';
        $.ligerDialog.error(message);
    };

    //表单验证
    security.validate = function (form, options) {
        if (typeof (form) == "string")
            form = $(form);
        else if (typeof (form) == "object" && form.NodeType == 1)
            form = $(form);

        options = $.extend({
            errorPlacement: function (lable, element) {
                if (!element.attr("id"))
                    element.attr("id", new Date().getTime());
                if (element.hasClass("l-textarea")) {
                    element.addClass("l-textarea-invalid");
                }
                else if (element.hasClass("l-text-field")) {
                    element.parent().addClass("l-text-invalid");
                }
                $(element).removeAttr("title").ligerHideTip();
                $(element).attr("title", lable.html()).ligerTip({
                    distanceX: 5,
                    distanceY: -3,
                    auto: true
                });
            },
            success: function (lable) {
                if (!lable.attr("for")) return;
                var element = $("#" + lable.attr("for"));

                if (element.hasClass("l-textarea")) {
                    element.removeClass("l-textarea-invalid");
                }
                else if (element.hasClass("l-text-field")) {
                    element.parent().removeClass("l-text-invalid");
                }
                $(element).removeAttr("title").ligerHideTip();
            }
        }, options || {});
        security.validator = form.validate(options);
        return security.validator;
    };



})(jQuery);


/**
 * js本地图片预览，兼容ie[6-9]、火狐、Chrome17+、Opera11+、Maxthon3
 * @param fileObj
 * @param imgPreviewId
 * @param divPreviewId
 * @returns
 */
function PreviewImage(fileObj, imgPreviewId, divPreviewId) {
	
    var allowExtention = ".jpg,.bmp,.gif,.png"; //允许上传文件的后缀名document.getElementById("hfAllowPicSuffix").value;
    var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
    var browserVersion = window.navigator.userAgent.toUpperCase();
    
    document.getElementById(divPreviewId).style.display = "inline";
    //本地地址
    $("#imgUrl").val(fileObj.value);
    //判断文件 大小
    var file = fileObj.files[0];
    
    var fileSize = file.size;
    
    var maxSize = 0.5 * 1024 * 1024;
    //文件 大小 不能大于1M
    if (fileSize > parseInt(maxSize)) {
    	security.alert("企业logo最大为512KB的图片，请尽量上传小图片logo");
    	document.getElementById(divPreviewId).style.display = "none";
    	$("#imgUrl").val("");
    	return false;
    }
    
    //error msg
    $("#error_img").attr("style","display:none");
    
    
    if (allowExtention.indexOf(extention) > -1) {
        if (fileObj.files) {//HTML5实现预览，兼容chrome、火狐7+等
            if (window.FileReader) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    document.getElementById(imgPreviewId).setAttribute("src", e.target.result);
                }
                reader.readAsDataURL(fileObj.files[0]);
            } else if (browserVersion.indexOf("SAFARI") > -1) {
                alert("不支持Safari6.0以下浏览器的图片预览!");
            }
        } else if (browserVersion.indexOf("MSIE") > -1) {
            if (browserVersion.indexOf("MSIE 6") > -1) {//ie6
                document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
            } else {//ie[7-9]
                fileObj.select();
                if (browserVersion.indexOf("MSIE 9") > -1)
                    fileObj.blur(); //不加上document.selection.createRange().text在ie9会拒绝访问
                var newPreview = document.getElementById(divPreviewId + "New");
                if (newPreview == null) {
                    newPreview = document.createElement("div");
                    newPreview.setAttribute("id", divPreviewId + "New");
                    newPreview.style.width = document.getElementById(imgPreviewId).width + "px";
                    newPreview.style.height = document.getElementById(imgPreviewId).height + "px";
                    newPreview.style.border = "solid 1px #d2e2e2";
                }
                newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
                var tempDivPreview = document.getElementById(divPreviewId);
                tempDivPreview.style.display = "inline";
                tempDivPreview.parentNode.insertBefore(newPreview, tempDivPreview);
                tempDivPreview.style.display = "none";
            }
        } else if (browserVersion.indexOf("FIREFOX") > -1) {//firefox
            var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1]);
            if (firefoxVersion < 7) {//firefox7以下版本
                document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());
            } else {//firefox7.0+                    
                document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));
            }
        } else {
            document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
        }
    } else {
        alert("仅支持" + allowExtention + "为后缀名的文件!");
        fileObj.value = ""; //清空选中文件
        if (browserVersion.indexOf("MSIE") > -1) {
            fileObj.select();
            document.selection.clear();
        }
        fileObj.outerHTML = fileObj.outerHTML;
    }
    return fileObj.value;    //返回路径
}


function gotoPage(formName,page) {
	$("#currentPage").val(page);
	var formSerialize = $("#"+formName).serializeObject();
	var v = JSON.stringify(formSerialize);
	$("#v").val(encodeURIComponent(v));
	$("#"+formName).submit();
}

function checkGoto(formName,gotoPageText,pageCount){
	var page = $("#"+gotoPageText).val();
	if (isNaN(page)) {
		security.alert("请输入合法数字");
		return false;
	}
	
	if (parseInt(page) > parseInt(pageCount)) {
		page = pageCount
	}
	
	gotoPage(formName,page);
	
}
